import logger          from "../base/log";
import * as HttpStatus from '../base/status';

// const env  = process.env.NODE_ENV || 'local';
// const opts = config[env];

export default function () {
    return async (ctx, next) => {
        ctx.rest = (data) => {
            let msg           = (typeof data == 'string') ? data : data.message;
            const result      = msg ? data.result : data;
            ctx.response.body = Object.assign({
                code: data.code || HttpStatus.CODE.OK,
            }, msg ? {message: msg} : {}, result ? {result: result} : {});

            logger(module.filename).info(`${ctx.request.method} ${ctx.request.url}`, ctx.response.body);
        };

        ctx.response.type = 'application/json';
        try {
            await next();
        } catch (e) {
            console.log(e);
            let body;
            if (e.name === 'invalid_scope')
                body = HttpStatus.UNAUTHORIZED;
            else {
                body = {
                    code   : e.code || HttpStatus.CODE.BAD_REQUEST,
                    message: e.message || 'unknown error'
                };
            }

            ctx.response.status = e.code || HttpStatus.CODE.BAD_REQUEST;
            ctx.response.body   = body;
        }
    }
};